//
//  wblistviewmodel.swift
//  weibo
//
//  Created by jason on 2017/3/5.
//  Copyright © 2017年 jason. All rights reserved.
//

import Foundation

///上拉刷新最大尝试次数
private let maxpulluptimes = 3

class wblistviewmodel{
    ///上拉刷新错误次数
    lazy var pulluperroetimes = 0
    //如果类需要使用kvc或者字典转模型框架,类就要继承nsobject
    //如果类只是包装一些代码逻辑,可以不用任何父类,好处,更加轻量级
    //使命:负责微博的数据处理
    lazy var statuslist = [wbstatus]()
    func loadstatus(pullup:Bool,completion:@escaping (_ issuccess:Bool,_ hasmorepullup:Bool)->()){
        //判断是否是上拉刷新,同时检查刷新错误
        if pullup && pulluperroetimes>maxpulluptimes{
            completion(true, false)
            return
        }
        //下拉刷新
        let since_id = pullup ? 0 : (statuslist.first?.id ?? 0)
        //上拉刷新
        let max_id = !pullup ? 0 : (statuslist.last?.id ?? 0)
        weibonetwork.shared.statuslist(since_id: since_id, max_id: max_id) { (list, issuccess) in
            //1.字典转模型
            guard let arry = NSArray.yy_modelArray(with: wbstatus.self, json: list ?? []) as? [wbstatus] else{
                completion(issuccess,false)
                return
            }
            print("刷新了\(arry.count)数据")
            //2.拼接数据
            if pullup{
                self.statuslist += arry
            }else{
                
                self.statuslist = arry + self.statuslist
            }
            //3.判断上拉刷新的数据量
            if pullup && arry.count == 0{
                self.pulluperroetimes += 1
                completion(issuccess,false)
            }else{
                completion(issuccess,true)
            }
            
            
        }
           }
}
